package org.sundatagroup.aurora.monitor.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.sundatagroup.aurora.monitor.entity.model.PlayListModel;

import java.util.List;

/**
 * <p>封装关于{@link PlayListModel}的DAO操作
 * </p>
 * 
 * @author CharlesChen
 * @date 2018-05-02
 * @since 0.1.1
 */
@Repository
public class PlayListDao {
    @Autowired
    MongoTemplate mongoOps;

    private final static Logger LOGGER = LoggerFactory.getLogger(PlayListDao.class);
    /**
     * 添加操作：添加一个{@link PlayListModel}
     * @param p
     */
    public void add(PlayListModel p) {
        mongoOps.insert(p);
    }

    /**
     * 查操作：根据播放列表命名查找
     * @param name 命名
     * @return
     */
    public PlayListModel findByName(String name) {
        PlayListModel plm;
        Query query = Query.query(Criteria.where("name").is(name));
        if ((plm = mongoOps.findOne(query,PlayListModel.class)) == null) {
            LOGGER.error("根据name查找播放列表失败，请检查！");
            return null;
        } else {
            return plm;
        }
    }
    /**
     * 查操作：根据播放列表ID查找。
     * @param lid ID
     * @return
     */
    public PlayListModel findByLid(int lid) {
        PlayListModel plm;
        Query query = Query.query(Criteria.where("lid").is(lid));
        if ((plm = mongoOps.findOne(query,PlayListModel.class)) == null) {
            LOGGER.error("根据ID查找播放列表失败，请检查！");
            return null;
        } else {
            return plm;
        }
    }

    /**
     * 返回所有的{@link PlayListModel}
     * @return
     */
    public List<PlayListModel> findAll() {
        List<PlayListModel> plms;
        if ((plms = mongoOps.findAll(PlayListModel.class)) == null) {
            LOGGER.error("查找所有播放列表失败");
            return null;
        } else {
            return plms;
        }
    }

    /**
     * 查操作：统计所有{@link PlayListModel}数量
     * @return
     */
    public int count() {
        return (int) mongoOps.count(new Query(), PlayListModel.class);
    }
}
